﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;

namespace HZ.Supervise.Web.Message
{
    public partial class WarningSetupTimeCompany : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindSort();
                BindList();
            }
        }

        /// <summary>
        /// 绑定药品类别
        /// </summary>
        private void BindSort()
        {
            HZ.Supervise.BLL.BLL_Sort bllSort = new HZ.Supervise.BLL.BLL_Sort();
            DataTable dtSort = bllSort.GetSort();
            ddlDrugSort.DataSource = dtSort;
            ddlDrugSort.DataTextField = "SortName";
            ddlDrugSort.DataValueField = "SortID";
            ddlDrugSort.DataBind();
            ddlDrugSort.Items.Insert(0, "---请选择---");
        }


        /// <summary>
        /// 制定消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnConfirmMessage_Click(object sender, EventArgs e)
        {
            //将数据存入数据库
            Model.MessageTypeDetail message = new HZ.Supervise.Model.MessageTypeDetail();
            message.AddTime = DateTime.Now;
            
            if (HZ.Fun.CheckString(hfdRecivedArea.Value.Trim()) != "")
            {
                message.AreaId = HZ.Fun.CheckString(hfdRecivedArea.Value.Trim().Trim(','));
                message.AreaName = HZ.Fun.CheckString(hfdRecivedAreaName.Value.Trim().Trim(','));
            }
            else
            {
                //return;
                message.AreaId = "";
                message.AreaName = "所有地区";
                //HZ.Web.WebUtil.Alert("请选择一个地区", this);
                //return;
            }
            if (HZ.Fun.CheckString(hdfRecivedCompany.Value.Trim()) != "")
            {
                message.CompanyId = HZ.Fun.CheckString(hdfRecivedCompany.Value.Trim().Trim(','));
                message.CompanyName = HZ.Fun.CheckString(hdfRecivedCompanyName.Value.Trim().Trim(','));
            }
            else
            {
                message.CompanyId = "";
                message.CompanyName = "所有企业";
                //HZ.Web.WebUtil.Alert("请选择一个企业", this);
                //return;
            }

            //药品类别
            if (HZ.Fun.CheckString(ddlDrugSort.SelectedValue) != "---请选择---")
            {
                message.SortId = HZ.Fun.CheckString(ddlDrugSort.SelectedValue.Trim());//药品分类编号
                message.SortName = HZ.Fun.CheckString(ddlDrugSort.SelectedItem.Text.Trim());//分类名称
            }
            else
            {
                message.SortId = "";
                message.SortName = "所有分类";
            }

            //所有药品信息
            if (HZ.Fun.CheckString(hdfRecivedGoods.Value) != "")
            {
                message.ProductName = HZ.Fun.CheckString(hdfRecivedGoodsName.Value.Trim().Trim(','));
                message.GoodsID = HZ.Fun.CheckString(hdfRecivedGoods.Value.Trim().Trim(','));
            }
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "")
            {
                message.ProductName = "所有药物";
            }
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "0")
            {
                message.ProductName = "日常采购";
            }
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "1")
            {
                message.ProductName = "临时采购";
            }
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "2")
            {
                message.ProductName = "应急采购";
            }

            //违规时间
            if (HZ.Fun.CheckString(txtTimeOfRange.Text.Trim()) == "")
            {
                HZ.Web.WebUtil.Alert("请选择触发条件！",this);
                return;
            }


            message.TypeId = int.Parse(ddlType.SelectedValue);
            message.TypeKey = "";
            message.TypeName = ddlType.SelectedItem.Text;
            message.UserId = CurrentAccount.UserID;
            message.Level = ddlLevel.SelectedItem.Text;
            message.Is_Work = false;
            message.MessageDetailId = Guid.NewGuid().ToString();
            message.SqlStringWhere = MakeSqlStringWhere(DateTime.Now);
            message.SqlDescription = MakeSqlDescription();
            message.Days = HZ.Fun.CheckString(txtTimeOfRange.Text.Trim()) == "" ? 1 : int.Parse(HZ.Fun.CheckString(txtTimeOfRange.Text.Trim()));
            message.DayType = ddlTime.SelectedItem.Text;
            message.Is_Del = false;//未删除
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            if (ibllMessage.IsExistMessageTypeDetail(message))
            {
				HZ.Web.WebUtil.Alert("规则重复", this);
                return;
            }
            int i = ibllMessage.InsertIntoMessageTypeDetail(message);
            if (i == 0)
            {
				HZ.Web.WebUtil.Alert("添加失败", this);
            }
            else
            {
				HZ.Web.WebUtil.Alert("添加成功", this);
                BindList();
                //清空
                txtArea.Text = "";
                txtDrug.Text = "";
                txtCompany.Text = "";
                txtTimeOfRange.Text = "";
                hdfRecivedGoods.Value = "";
                hdfRecivedCompany.Value = "";
                hfdRecivedArea.Value = "";
                hfdRecivedAreaName.Value = "";
                ddlDrugSort.SelectedValue = "---请选择---";
                ddlLevel.SelectedValue = "0";
                ddlTime.SelectedValue = "0";
            }
        }
        /// <summary>
        /// 生成Where语句
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        protected string MakeSqlStringWhere(DateTime time)
        {
            StringBuilder sb = new StringBuilder("", 255);

            if (!string.IsNullOrEmpty(txtTimeOfRange.Text.Trim()))
            {
                if (ddlType.SelectedItem.Value == "4")
                {
                    switch (ddlTime.SelectedItem.Text)
                    {

                        case "日":
                            string timeday = string.Format("DATEADD({0},{1}, '{2}')", "day", txtTimeOfRange.Text.Trim(), time);
                            sb.AppendFormat(" ReturnTime>'{1}' and ReturnTime<{0}", timeday, time);
                            break;
                        case "周":
                            string timeweek = string.Format("DATEADD({0},{1}, '{2}')", "week", txtTimeOfRange.Text.Trim(), time);
                            sb.AppendFormat(" ReturnTime>'{1}' and ReturnTime<{0}", timeweek, time);
                            break;
                        case "月":
                            string timemonth = string.Format("DATEADD({0},{1}, '{2}')", "month", txtTimeOfRange.Text.Trim(), time);
                            sb.AppendFormat(" ReturnTime>'{1}' and ReturnTime<{0}", timemonth, time);
                            break;
                    }
                }

                else
                {
                    switch (ddlTime.SelectedItem.Text)
                    {

                        case "日":
                            string timeday = string.Format("DATEADD({0},{1}, '{2}')", "day", txtTimeOfRange.Text.Trim(), time);
                            sb.AppendFormat(" ExecuteTime>'{1}' and ExecuteTime<{0}", timeday, time);
                            break;
                        case "周":
                            string timeweek = string.Format("DATEADD({0},{1}, '{2}')", "week", txtTimeOfRange.Text.Trim(), time);
                            sb.AppendFormat(" ExecuteTime>'{1}' and ExecuteTime<{0}", timeweek, time);
                            break;
                        case "月":
                            string timemonth = string.Format("DATEADD({0},{1}, '{2}')", "month", txtTimeOfRange.Text.Trim(), time);
                            sb.AppendFormat(" ExecuteTime>'{1}' and ExecuteTime<{0}", timemonth, time);
                            break;
                    }
                }

            }

            if (ddlSortSource.SelectedValue.ToString() != "")
            {
                sb.AppendFormat(" AND SortSource={0} ", ddlSortSource.SelectedValue.ToString());
            }

            //if (ddlType.SelectedValue.ToString() == "3")
            //{

            //    if (ddlSortSource.SelectedValue != "")
            //    {
            //        sb.AppendFormat(" AND SortSource={0} ", ddlSortSource.SelectedValue.ToString());
            //    }
            //}
            //else if (ddlType.SelectedValue.ToString() == "4")
            //{

            //    if (ddlSortSource.SelectedValue != "")
            //    {
            //        sb.AppendFormat(" AND SortSource={0} ", ddlSortSource.SelectedValue.ToString());
            //    }
            //}
            #region 地区医院
            if (hdfRecivedCompany.Value.Trim() != "")
            {
                if (ddlType.SelectedValue.Equals("4"))
                    sb.AppendFormat(" AND CompanyId IN({0}) ", MakeQueryIn(hdfRecivedCompany.Value.Trim().TrimEnd(',')));
                else
                    sb.AppendFormat(" AND CompanyId_PS IN({0}) ", MakeQueryIn(hdfRecivedCompany.Value.Trim().TrimEnd(',')));
            }
            else
            {
                if (hfdRecivedArea.Value.Trim() != "")
                {
                    sb.AppendFormat(" AND AreaId IN({0}) ", MakeQueryIn(hfdRecivedArea.Value.Trim().TrimEnd(',')));
                }
            }
            #endregion
            #region 药品
            if (hdfRecivedGoods.Value.Trim() != "")
            {
                sb.AppendFormat(" AND GoodsId IN({0}) ", MakeQueryIn(hdfRecivedGoods.Value.Trim().TrimEnd(',')));
            }
            else
            {
                if (ddlDrugSort.SelectedValue.ToString() != "---请选择---")
                {
                    sb.AppendFormat(" AND SortId='{0}' ", ddlDrugSort.SelectedValue.ToString());
                }

            }
            #endregion
            return sb.ToString();
        }


        protected string MakeQueryIn(string msg)
        {
            StringBuilder sb = new StringBuilder();
            string[] arr = msg.Trim().Split(',');
            for (int i = 0; i < arr.Length; i++)
            {
                if (i == 0)
                {
                    sb.AppendFormat("'{0}'", arr[i]);
                }
                else
                {
                    sb.AppendFormat(",'{0}'", arr[i]);
                }
            }
            return sb.ToString();
        }
        /// <summary>
        /// 生成Sql描述语句
        /// </summary>
        /// <returns></returns>
        protected string MakeSqlDescription()
        {
            StringBuilder sb = new StringBuilder("", 255);
            if (!string.IsNullOrEmpty(txtTimeOfRange.Text.Trim()))
            {
                sb.AppendFormat("违规时间为<font color='RED'>{0}</font>{1}", int.Parse(HZ.Fun.CheckString(txtTimeOfRange.Text.Trim())), ddlTime.SelectedItem.Text);
            }
            return sb.ToString();
        }
        /// <summary>
        /// 数据绑定
        /// </summary>
        void BindList()
        {
            int t = 0;
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            Model.MessageTypeDetail messageTypeDetail = new HZ.Supervise.Model.MessageTypeDetail();
            messageTypeDetail.UserId = CurrentAccount.UserID;
            messageTypeDetail.Is_Work = false;
            messageTypeDetail.Is_Del = false;
            gvwWarningStart.DataSource = ibllMessage.GetMessageTypeDetailByType(messageTypeDetail, "3,4,5,8,9,10", AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out t);
            this.AspNetPager1.RecordCount = t;
            gvwWarningStart.DataBind();
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindList();
        }
        /// <summary>
        /// 行数据绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwWarningStart_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            for (int i = 0; i < gvwWarningStart.Rows.Count; i++)
            {
                string areaName = ((Label)(gvwWarningStart.Rows[i].Cells[2].FindControl("lblAreaName"))).Text.ToString();
                if (!string.IsNullOrEmpty(areaName))
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[2].FindControl("lblAreaName"))).Text = SubStr(areaName, 12);
                }
                else
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[2].FindControl("lblAreaName"))).Text = "所有地区";
                }



                string hospitalName = ((Label)(gvwWarningStart.Rows[i].Cells[1].FindControl("lblHospitalName"))).Text.ToString();
                if (hospitalName != "")
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[1].FindControl("lblHospitalName"))).Text = SubStr(hospitalName, 12);
                }
                else
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[1].FindControl("lblHospitalName"))).Text = "所有企业";
                }

                string productName = ((Label)(gvwWarningStart.Rows[i].Cells[4].FindControl("lblProductName"))).Text.ToString();
                if (productName != "")
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[4].FindControl("lblProductName"))).Text = SubStr(productName, 12);
                }
                else
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[4].FindControl("lblProductName"))).Text = "所有药品";
                }
                string SortName = ((Label)(gvwWarningStart.Rows[i].Cells[5].FindControl("lblSortName"))).Text.ToString();
                if (SortName != "---请选择---")
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[5].FindControl("lblSortName"))).Text = SubStr(SortName, 12);
                }
                else
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[5].FindControl("lblSortName"))).Text = "所有分类";
                }
            }
        }
        /// <summary>
        /// 字符串截取
        /// </summary>
        /// <param name="sString"></param>
        /// <param name="nLeng"></param>
        /// <returns></returns>
        string SubStr(string sString, int nLeng)
        {
            if (sString.Length <= nLeng)
            {
                return sString;
            }
            string sNewStr = sString.Substring(0, nLeng);
            sNewStr = sNewStr + "...";
            return sNewStr;
        }
        /// <summary>
        /// 删除预警
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelte_Click(object sender, EventArgs e)
        {
            string chkedids = Request.Form["chk"];
            int flag = 1;
            if (string.IsNullOrEmpty(chkedids))
            {
				HZ.Web.WebUtil.Alert("请选择一个规则！", this);
                return;
            }
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            foreach (var item in chkedids.Split(','))
            {
                flag = ibllMessage.DeleteMessageTypeDetail(item);
            }
            if (flag == 1)
            {
				HZ.Web.WebUtil.Alert("删除成功！", this);
            }
            else
            {
				HZ.Web.WebUtil.Alert("删除失败！", this);
            }
            BindList();
        }
        /// <summary>
        /// 启用预警
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnStart_Click(object sender, EventArgs e)
        {
            string chkedids = Request.Form["chk"];
            int flag = 1;
            if (string.IsNullOrEmpty(chkedids))
            {
				HZ.Web.WebUtil.Alert("请选择一个规则！", this);
                return;
            }
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            foreach (var item in chkedids.Split(','))
            {
                flag = ibllMessage.WarningSwitch(item, "1");
            }
            if (flag == 1)
            {
				HZ.Web.WebUtil.Alert("启用成功！", this);
            }
            else
            {
				HZ.Web.WebUtil.Alert("启用失败！", this);
            }
            BindList();
        }
    }
}
